package com.fau.mm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.mm.entity.MedicalAdmin;
import com.fau.mm.entity.MedicalCity;
import com.fau.mm.entity.MedicalDistrict;
import com.fau.mm.entity.MedicalEnterpriseOutside;
import com.fau.mm.entity.MedicalKeyValue;
import com.fau.mm.entity.MedicalMediaInfo;
import com.fau.mm.entity.MedicalMediaInfoCosts;
import com.fau.mm.entity.MedicalMediaPlacement;
import com.fau.mm.entity.MedicalMedicine;
import com.fau.mm.entity.MedicalProvince;
import com.fau.mm.service.IMediaManagerService;
import com.fau.mm.util.Page;
import com.fau.mm.util.ParamUtil;
import com.fau.mm.util.SystemConfig;
import com.fau.mm.util.ValidatorUtil;

@Service
@Transactional(readOnly = true)
public class MediaManagerService extends BaseService implements IMediaManagerService {

	@Override
	public Page findAllMediaInfo(Map<String, Object> map, MedicalMediaInfo info) {
		StringBuilder statusSql = new StringBuilder("from MedicalMediaInfo a where 1=1 and a.eid = ? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalMediaInfo a where 1=1 and a.eid = ? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(info.getEid());
		
		if(StringUtils.isNotBlank(info.getName())){
			statusSql.append(" and a.name = ? ");
			countSql.append(" and a.name = ? ");
			objectList.add(info.getName());
		}
		
		if(StringUtils.isNotBlank(info.getAddress())){
			String address = info.getAddress().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			statusSql.append(" and a.address like ? ");
			countSql.append(" and a.address like ? ");
			objectList.add("%"+address+"%");
		}
		
		if(StringUtils.isNotBlank(info.getPostCode())){
			statusSql.append(" and a.postCode = ? ");
			countSql.append(" and a.postCode = ? ");
			objectList.add(info.getPostCode());
		}
		
		if(StringUtils.isNotBlank(info.getPhoneNum())){
			statusSql.append(" and a.phoneNum = ? ");
			countSql.append(" and a.phoneNum = ? ");
			objectList.add(info.getPhoneNum());
		}
		
		if(StringUtils.isNotBlank(info.getFax())){
			statusSql.append(" and a.fax = ? ");
			countSql.append(" and a.fax = ? ");
			objectList.add(info.getFax());
		}
		
		if(StringUtils.isNotBlank(info.getLinkMan())){
			statusSql.append(" and a.linkMan = ? ");
			countSql.append(" and a.linkMan = ? ");
			objectList.add(info.getLinkMan());
		}
		
		if(StringUtils.isNotBlank(info.getUrl())){
			String url = info.getUrl().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			statusSql.append(" and a.url like ? ");
			countSql.append(" and a.url like ? ");
			objectList.add("%"+url+"%");
		}
		
		if(StringUtils.isNotBlank(info.getEmail())){
			statusSql.append(" and a.email = ? ");
			countSql.append(" and a.email = ? ");
			objectList.add(info.getEmail());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		return this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean save(MedicalMediaInfo info, MedicalAdmin admin) {
		info.setEid(admin.getEnterpriseId());
		MedicalAdmin user = new MedicalAdmin();
		user.setId(admin.getId());
		info.setUser(user);
		Set<ConstraintViolation<Object>> errorInfo = ValidatorUtil.validateObj(info);
		if(errorInfo.size() > 0) {
			return false;
		} else {
			return this.iBaseDao.saveObject(info);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean saveEdit(MedicalMediaInfo info, MedicalAdmin admin) {
		MedicalMediaInfo media = (MedicalMediaInfo) this.iBaseDao.getObject(MedicalMediaInfo.class, info.getId());
		media.setName(info.getName());
		media.setAddress(info.getAddress());
		media.setProvinceId(info.getProvinceId());
		media.setCityId(info.getCityId());
		media.setDistrictId(info.getDistrictId());
		media.setPostCode(info.getPostCode());
		media.setPhoneNum(info.getPhoneNum());
		media.setFax(info.getFax());
		media.setLinkMan(info.getLinkMan());
		media.setUrl(info.getUrl());
		media.setEmail(info.getEmail());
		media.setUser(admin);
		media.setDescription(info.getDescription());
		media.setUpdateTime(new Date());
		Set<ConstraintViolation<Object>> errorInfo = ValidatorUtil.validateObj(media);
		if(errorInfo.size() > 0) {
			return false;
		} else {
			return this.iBaseDao.saveObject(media);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean delete(MedicalMediaInfo info) {
		String str[] = info.getId().split(",");
		if(str.length == 1){
			int count = this.iBaseDao.getIntCount("select count(*) from MedicalOrdersStorage m where m.mediaId = ? ", str[0]);
			if(count > 0) {
				return false;
			}
			this.iBaseDao.deleteObject(info);
		}else{
			for(String id : str) {
				int count = this.iBaseDao.getIntCount("select count(*) from MedicalOrdersStorage m where m.mediaId = ? ", id);
				if(count > 0) {
					return false;
				}
			}
			for(String id : str){
				this.iBaseDao.updateHql("delete from MedicalMediaInfo m where m.id = ? ", id);
			}
		}
		return true;
	}

	@Override
	public Workbook currentPage(String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_INFO);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] mIds =  ids.split(",");
			for(int j=0;j<mIds.length;j++){
				// 获得记录
				MedicalMediaInfo info = (MedicalMediaInfo)this.iBaseDao.getObject(MedicalMediaInfo.class, mIds[j]);
				if(null != info){
					Row currentRow = sheet.createRow(++i);
					currentRow.createCell(0).setCellValue(i);
					currentRow.createCell(1).setCellValue(info.getName());
					currentRow.createCell(2).setCellValue(info.getLinkMan());
					currentRow.createCell(3).setCellValue(info.getEmail());
					currentRow.createCell(4).setCellValue(info.getPhoneNum());
					currentRow.createCell(5).setCellValue(info.getPostCode());
					currentRow.createCell(6).setCellValue(info.getFax());
					currentRow.createCell(7).setCellValue(info.getUrl());
					currentRow.createCell(8).setCellValue(info.getAddress());
					if(null != info.getCreateTime()){
						currentRow.createCell(9).setCellValue(DateFormatUtils.format(info.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
					}
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("all")
	@Override
	public Workbook allPage(MedicalAdmin admin) throws Exception {
		List<MedicalMediaInfo> list = this.iBaseDao.getBySql("from MedicalMediaInfo m where 1=1 and m.eid = ? order by m.createTime desc", null, admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_INFO);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		for(MedicalMediaInfo info : list){
			i++;
			if(null != info){
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				currentRow.createCell(1).setCellValue(info.getName());
				currentRow.createCell(2).setCellValue(info.getLinkMan());
				currentRow.createCell(3).setCellValue(info.getEmail());
				currentRow.createCell(4).setCellValue(info.getPhoneNum());
				currentRow.createCell(5).setCellValue(info.getPostCode());
				currentRow.createCell(6).setCellValue(info.getFax());
				currentRow.createCell(7).setCellValue(info.getUrl());
				currentRow.createCell(8).setCellValue(info.getAddress());
				if(null != info.getCreateTime()){
					currentRow.createCell(9).setCellValue(DateFormatUtils.format(info.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
				}
			}
		}
		return workbook;
	}

	@Override
	public Page findAllMediaPlacement(Map<String, Object> map, MedicalMediaPlacement place, MedicalAdmin admin) {
		StringBuilder statusSql = new StringBuilder("from MedicalMediaPlacement a where 1=1 and a.media.eid = ? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalMediaPlacement a where 1=1 and a.media.eid = ? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		
		if(StringUtils.isNotBlank(place.getMedicineId())){
			String str[] = place.getMedicineId().split(",");
			statusSql.append(" and (a.medicine.id = ? ");
			countSql.append(" and (a.medicine.id = ? ");
			objectList.add(str[0]);
			if(str.length > 1){
				for(int i=1;i<str.length;i++){
					statusSql.append(" or a.medicine.id = ? ");
					countSql.append(" or a.medicine.id = ? ");
					objectList.add(str[i]);
				}
			}
			statusSql.append(")");
			countSql.append(")");
		}
		if(StringUtils.isNotBlank(place.getMediaId())){
			String str[] = place.getMediaId().split(",");
			statusSql.append(" and (a.media.id = ? ");
			countSql.append(" and (a.media.id = ? ");
			objectList.add(str[0]);
			if(str.length > 1){
				for(int i=1;i<str.length;i++){
					statusSql.append(" or a.media.id = ? ");
					countSql.append(" or a.media.id = ? ");
					objectList.add(str[i]);
				}
			}
			statusSql.append(")");
			countSql.append(")");
		}
		
		if(null != place.getPlaceStartTime()){
			statusSql.append(" and a.placeStartTime >= ? ");
			countSql.append(" and a.placeStartTime >= ? ");
			objectList.add(place.getPlaceStartTime());
		}
		
		if(null != place.getPlaceEndTime()){
			statusSql.append(" and a.placeEndTime =< ? ");
			countSql.append(" and a.placeEndTime =< ? ");
			objectList.add(place.getPlaceEndTime());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalMediaPlacement> list = new ArrayList<MedicalMediaPlacement>();
		for(Object obj : page.getResult()){
			MedicalMediaPlacement bean = (MedicalMediaPlacement) obj;
			MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), bean.getPlaying());
			bean.setPlay(keyValue.getKeyValue());
			list.add(bean);
		}
		page.setResult(list);
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean savePlace(MedicalMediaPlacement place) {
		MedicalMedicine medicine = new MedicalMedicine();
		medicine.setId(place.getMedicineId());
		place.setMedicine(medicine);
		MedicalMediaInfo info = new MedicalMediaInfo();
		info.setId(place.getMediaId());
		place.setMedia(info);
		Set<ConstraintViolation<Object>> errorInfo = ValidatorUtil.validateObj(place);
		if(errorInfo.size() > 0) {
			return false;
		} else {
			return this.iBaseDao.saveObject(place);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean saveEditPlace(MedicalMediaPlacement place, MedicalAdmin admin) {
		MedicalMediaPlacement bean = (MedicalMediaPlacement) this.iBaseDao.getObject(MedicalMediaPlacement.class, place.getId());
		MedicalMedicine medicine = new MedicalMedicine();
		medicine.setId(place.getMedicineId());
		bean.setMedicine(medicine);
		MedicalMediaInfo media = new MedicalMediaInfo();
		media.setId(place.getMediaId());
		bean.setMedia(media);
		bean.setPublishNumbers(place.getPublishNumbers());
		bean.setCosts(place.getCosts());
		bean.setPlaceStartTime(place.getPlaceStartTime());
		bean.setPlaceEndTime(place.getPlaceEndTime());
		bean.setStartTime(place.getStartTime());
		bean.setEndTime(place.getEndTime());
		bean.setPlaying(place.getPlaying());
		bean.setDescription(place.getDescription());
		bean.setUpdateTime(new Date());
		Set<ConstraintViolation<Object>> errorInfo = ValidatorUtil.validateObj(bean);
		if(errorInfo.size() > 0) {
			return false;
		} else {
			return this.iBaseDao.saveObject(bean);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void deletePlace(MedicalMediaPlacement place) {
		String str[] = place.getId().split(",");
		if(str.length == 1){
			this.iBaseDao.deleteObject(place);
		}else{
			for(String id : str){
				this.iBaseDao.updateHql("delete from MedicalMediaPlacement m where m.id = ? ", id);
			}
		}
	}

	@Override
	public Workbook currentPagePlace(String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_PLACEMENT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		CellStyle style = workbook.createCellStyle();
		style.setWrapText(true);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] mIds =  ids.split(",");
			for(int j=0;j<mIds.length;j++){
				// 获得记录
				MedicalMediaPlacement place = (MedicalMediaPlacement)this.iBaseDao.getObject(MedicalMediaPlacement.class, mIds[j]);
				if(null != place){
					Row currentRow = sheet.createRow(++i);
					currentRow.createCell(0).setCellValue(i);
					currentRow.createCell(1).setCellValue(place.getMedicine().getName());
					currentRow.createCell(2).setCellValue(place.getMedia().getName());
					if(null != place.getPlaceStartTime()){
						currentRow.createCell(3).setCellValue(DateFormatUtils.format(place.getPlaceStartTime(), "yyyy-MM-dd HH:mm:ss"));
					}
					if(null != place.getPlaceEndTime()){
						currentRow.createCell(4).setCellValue(DateFormatUtils.format(place.getPlaceEndTime(), "yyyy-MM-dd HH:mm:ss"));
					}
					currentRow.createCell(5).setCellStyle(style);
					currentRow.createCell(5).setCellValue(place.getDescription());
					currentRow.createCell(6).setCellValue(place.getStartTime());
					currentRow.createCell(7).setCellValue(place.getEndTime());
					if(StringUtils.isNotBlank(place.getPlaying())){
						MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(place.getMedia().getEid(), place.getPlaying());
						if(null != keyValue){
							currentRow.createCell(8).setCellValue(keyValue.getKeyValue());
						}
					}
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Workbook allPagePlace(MedicalAdmin admin) throws Exception {
		List<MedicalMediaPlacement> list = this.iBaseDao.getBySql("from MedicalMediaPlacement m where 1=1 and m.media.eid = ? order by m.createTime desc", null, admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_PLACEMENT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		for(MedicalMediaPlacement place : list){
			i++;
			if(null != place){
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				currentRow.createCell(1).setCellValue(place.getMedicine().getName());
				currentRow.createCell(2).setCellValue(place.getMedia().getName());
				if(null != place.getPlaceStartTime()){
					currentRow.createCell(3).setCellValue(DateFormatUtils.format(place.getPlaceStartTime(), "yyyy-MM-dd HH:mm:ss"));
				}
				if(null != place.getPlaceEndTime()){
					currentRow.createCell(4).setCellValue(DateFormatUtils.format(place.getPlaceEndTime(), "yyyy-MM-dd HH:mm:ss"));
				}
				currentRow.createCell(5).setCellValue(place.getDescription());
				currentRow.createCell(6).setCellValue(place.getStartTime());
				currentRow.createCell(7).setCellValue(place.getEndTime());
				if(StringUtils.isNotBlank(place.getPlaying())){
					MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(place.getMedia().getEid(), place.getPlaying());
					if(null != keyValue){
						currentRow.createCell(8).setCellValue(keyValue.getKeyValue());
					}
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalMedicine> findAllMedicineByEid(String eid) {
		return this.iBaseDao.getBySql("from MedicalMedicine m where m.hospitalId = ? ", null, eid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalMediaInfo> findAllMediaByEid(String eid) {
		return this.iBaseDao.getBySql("from MedicalMediaInfo m where m.eid = ? ", null, eid);
	}

	@Override
	public List<MedicalKeyValue> getKeyValue(String eid, String type) {
		return this.iBaseDao.findValueByType(eid, SystemConfig.MM_SYSTEM_TYPE, type);
	}

	@Override
	public Page findAllMediaInfoCost(Map<String, Object> map, MedicalMediaInfoCosts cost, MedicalAdmin admin) {
		StringBuilder statusSql = new StringBuilder("from MedicalMediaInfoCosts a where 1=1 and a.eid = ? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalMediaInfoCosts a where 1=1 and a.eid = ? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		
		if(StringUtils.isNotBlank(cost.getMedicineId())){
			String str[] = cost.getMedicineId().split(",");
			statusSql.append(" and (a.medicineId = ? ");
			countSql.append(" and (a.medicineId = ? ");
			objectList.add(str[0]);
			if(str.length > 1){
				for(int i=1;i<str.length;i++){
					statusSql.append(" or a.medicineId = ? ");
					countSql.append(" or a.medicineId = ? ");
					objectList.add(str[i]);
				}
			}
			statusSql.append(")");
			countSql.append(")");
		}
		if(StringUtils.isNotBlank(cost.getMediaId())){
			String str[] = cost.getMediaId().split(",");
			statusSql.append(" and (a.mediaId = ? ");
			countSql.append(" and (a.mediaId = ? ");
			objectList.add(str[0]);
			if(str.length > 1){
				for(int i=1;i<str.length;i++){
					statusSql.append(" or a.mediaId = ? ");
					countSql.append(" or a.mediaId = ? ");
					objectList.add(str[i]);
				}
			}
			statusSql.append(")");
			countSql.append(")");
		}
		
		
//		if(null != bean.getStartTime()){
//			statusSql.append(" and (a.createTime > ? ");
//			countSql.append(" and (a.createTime > ? ");
//			objectList.add(bean.getStartTime());
//			statusSql.append(" and a.createTime < ? )");
//			countSql.append(" and a.createTime < ? )");
//			objectList.add(DateUtil.getDate(bean.getStartTime()));
//		}else{
//			statusSql.append(" and a.createTime > ? ");
//			countSql.append(" and a.createTime > ? ");
//			objectList.add(DateUtil.getDates(true, 0));
//			statusSql.append(" and a.createTime < ? ");
//			countSql.append(" and a.createTime < ? ");
//			objectList.add(DateUtil.getDates(false, 0));
//		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		return this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
	}

	@Override
	public Workbook currentPageCost(String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_COSTS);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		CellStyle style = workbook.createCellStyle();
		style.setWrapText(true);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] mIds =  ids.split(",");
			for(int j=0;j<mIds.length;j++){
				// 获得记录
				MedicalMediaInfoCosts cost = (MedicalMediaInfoCosts)this.iBaseDao.getObject(MedicalMediaInfoCosts.class, mIds[j]);
				if(null != cost){
					Row currentRow = sheet.createRow(++i);
					currentRow.createCell(0).setCellValue(i);
					currentRow.createCell(1).setCellValue(cost.getMedicineName());
					currentRow.createCell(2).setCellValue(cost.getMediaName());
					currentRow.createCell(3).setCellValue(DateFormatUtils.format(cost.getPutTime(), "yyyy-MM-dd"));
					currentRow.createCell(4).setCellValue(cost.getInNum());
					currentRow.createCell(5).setCellValue(String.valueOf(cost.getDailyCost()));
					currentRow.createCell(6).setCellValue(cost.getOrderNum());
					currentRow.createCell(7).setCellValue(String.valueOf(cost.getOrderCost()));
					currentRow.createCell(8).setCellValue(String.valueOf(cost.getEffectiveCost()));
					currentRow.createCell(9).setCellStyle(style);
					currentRow.createCell(9).setCellValue(cost.getDescription());
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Workbook allPageCost(MedicalAdmin admin) throws Exception {
		List<MedicalMediaInfoCosts> list = this.iBaseDao.getBySql("from MedicalMediaInfoCosts m where 1=1 and m.eid = ? order by m.createTime desc", null, admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(com.fau.mm.util.SystemConfig.EXPORT_MEDIA_PLACEMENT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		CellStyle style = workbook.createCellStyle();
		style.setWrapText(true);
		int i=0;
		for(MedicalMediaInfoCosts cost : list){
			i++;
			if(null != cost){
				Row currentRow = sheet.createRow(++i);
				currentRow.createCell(0).setCellValue(i);
				currentRow.createCell(1).setCellValue(cost.getMedicineName());
				currentRow.createCell(2).setCellValue(cost.getMediaName());
				currentRow.createCell(3).setCellValue(DateFormatUtils.format(cost.getPutTime(), "yyyy-MM-dd"));
				currentRow.createCell(4).setCellValue(cost.getInNum());
				currentRow.createCell(5).setCellValue(String.valueOf(cost.getDailyCost()));
				currentRow.createCell(6).setCellValue(cost.getOrderNum());
				currentRow.createCell(7).setCellValue(String.valueOf(cost.getOrderCost()));
				currentRow.createCell(8).setCellValue(String.valueOf(cost.getEffectiveCost()));
				currentRow.createCell(9).setCellStyle(style);
				currentRow.createCell(9).setCellValue(cost.getDescription());
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalProvince> findProvinceList() {
		return this.iBaseDao.getBySql("from MedicalProvince ", null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCity> findCityListByPid(String pId) {
		return this.iBaseDao.getBySql("from MedicalCity a where a.pId=? ", null, pId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalDistrict> findDistrictListByCid(String cId) {
		return this.iBaseDao.getBySql("from MedicalDistrict a where a.cId=? ", null, cId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalEnterpriseOutside> findOutline() {
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<MedicalEnterpriseOutside> list = this.iBaseDao.getBySql("from MedicalEnterpriseOutside a where a.eid=? ", null, admin.getEnterpriseId());
		return list;
	}
	
}
